<template>
  <div class="app-container pro_cate_mgr_content">
    <el-form class="formList" :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch"
      label-width="80px">
      <el-row>

        <el-form-item label="类别名称" prop="categoryName">
          <el-input v-model="queryParams.categoryName" placeholder="请输入类别名称" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>

        <el-form-item label="层级" prop="categoryDepth">
          <el-select v-model="queryParams.categoryDepth" placeholder="请选择层级" clearable size="small">
            <el-option v-for="dict in categoryDepthOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue" />
          </el-select>
        </el-form-item>


        <el-form-item label="是否展示" prop="isShow">
          <el-select v-model="queryParams.isShow" placeholder="请选择" clearable size="small">
            <el-option v-for="dict in isShowOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue" />
          </el-select>
        </el-form-item>

      </el-row>
      <el-row>

       

        <el-form-item label="状态" prop="dataStatus">
          <el-select v-model="queryParams.dataStatus" placeholder="状态" clearable size="small">
            <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue" />
          </el-select>
        </el-form-item>

        <el-form-item style="margin-left: 22px;">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>

      </el-row>
    </el-form>

    <el-row class="row-mbinfo">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['proboxServiceItem:category:add']">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <div class="divTable">
      <el-table border v-loading="loading" :data="categoryList" row-key="categoryUid"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}">

        <el-table-column label="类别信息" align="center" prop="categoryImgUrl" width="200px;">
          <template slot-scope="scope">
            <div class="show_cate_info">
              <el-image style="width: 30px;height: 30px;border-radius: 50%;margin: 0 5px"
                v-if="scope.row.categoryImgUrl != null && scope.row.categoryImgUrl != '' " slot="reference"
                :src="scope.row.categoryImgUrl" :preview-src-list="[scope.row.categoryImgUrl]">
              </el-image>
              <span :class="isNull(scope.row.categoryImgUrl) == true ?  'img-text' : ''"> {{scope.row.categoryName}}
              </span>
            </div>
          </template>
        </el-table-column>


        <el-table-column label="层级" align="center" prop="categoryDepth" :formatter="categoryDepthFormat" />

        <el-table-column label="状态" align="center" prop="dataStatus">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.dataStatus" active-value="1" inactive-value="0"
              @change="handleStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>

        <el-table-column label="类别banner图" align="center" prop="categoryBanner">
          <template slot-scope="scope">
            <el-image style="width: 30px;height: 30px;"
              v-if="scope.row.categoryBanner != null && scope.row.categoryBanner != '' " slot="reference"
              :src="scope.row.categoryBanner" :preview-src-list="[scope.row.categoryBanner]">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="是否展示" align="center" prop="isShow">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.isShow" active-value="1" inactive-value="0"
              @change="handleShowChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
 
        <el-table-column label="排序" align="center" prop="dataPriority" sortable />
        <el-table-column label="更新时间" align="center" prop="updateTime" width="180" sortable>
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['proboxServiceItem:category:edit']">修改</el-button>
            <el-button v-if="scope.row.categoryDepth != 1 " size="mini" type="text" icon="el-icon-plus"
              @click="handleAdd(scope.row)" v-hasPermi="['proboxServiceItem:category:add']">新增</el-button>
            <el-button v-if="scope.row.dataStatus == '0' " size="mini" type="text" icon="el-icon-delete"
              @click="handleDelete(scope.row)" v-hasPermi="['proboxServiceItem:category:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 添加或修改服务类别对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="750px" append-to-body @keyup.enter.native="submitForm">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="上级类别" prop="categoryPuid">
          <el-select v-model="form.categoryPuid" placeholder="请选择类别" clearable>
            <el-option v-for="cate in categoryDepthList" :key="cate.categoryUid" :label="cate.categoryName"
              :value="cate.categoryUid" class="input-rule" />
          </el-select>
        </el-form-item>


        <el-form-item hidden>
          <el-input type="hidden" v-model="form.categoryDepth" placeholder="请输入类别等级" class="select-normal" />
        </el-form-item>

        <el-row :gutter="24">
          <el-col :span="7">
            <el-form-item label="类别名称" prop="categoryName">
              <el-input v-model="form.categoryName" placeholder="请输入类别名称" class="select-normal" maxlength="10"
                show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="类别图片">
          <imageArraySize :imageStr.sync="form.categoryImgUrl" :key="form.categoryImgUrl"
            :msg="'图片要求：宽高200px*200px，大小1M内。'"  :limit="1" ref="child"></imageArraySize>
        </el-form-item>
        <el-form-item label="banner图" style="margin-top: -22px;">
          <imageArraySize :imageStr.sync="form.categoryBanner" :key="form.categoryBanner" :width="130" :height="100"
            :msg="'图片要求：宽750px高563px，大小1M内。'"  :limit="1" ref="childs"></imageArraySize>
        </el-form-item>
        <el-form-item label="是否展示" style="margin-top: -12px;">
          <el-radio-group v-model="form.isShow">
            <el-radio v-for="dict in isShowOptions" :key="dict.dictValue" :label="dict.dictValue">{{dict.dictLabel}}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="数据状态">
          <el-radio-group v-model="form.dataStatus">
            <el-radio label="1">有效</el-radio>
            <el-radio label="0">无效</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-row :gutter="24">
          <el-col :span="7">
            <el-form-item label="排序" prop="dataPriority">
              <el-input-number v-model="form.dataPriority" size="small" placeholder="请输入排序" controls-position="right"
                :min="0" class="select-normal" :max="999999" />
            </el-form-item>
          </el-col>
        </el-row>

       

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {
    listCategory,
    getCategory,
    delCategory,
    addCategory,
    updateCategory,
    exportCategory,
    updateCategoryStatus,
    listCategoryDepth,
    updateCategoryIsShow
  } from "@/api/service/serviceCategory";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import imageArraySize from "@/components/ImageUpload/imageArraySize";

  export default {
    name: "Category",
    components: {
      imageArraySize,
      Treeselect
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 显示搜索条件
        showSearch: true,
        // 服务类别表格数据
        categoryList: [],
        // 服务类别树选项
        categoryOptions: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 层级类别
        categoryDepthList: [],
        // 是否展示(1/展示，0/不展示)字典
        isShowOptions: [],
        // 层级数据字典
        categoryDepthOptions: [
        {
          dictValue: "0",
          dictLabel: "一级",
        },
        {
          dictValue: "1",
          dictLabel: "二级",
        },
      ],
        // 常用数据状态字典
        statusOptions: [],
        // 发货时间字典
        arrivalTimeOptions: [],
        // 查询参数
        queryParams: {
          categoryName: null,
          dataStatus: null,
          categoryDepth: null,
          isShow: null,
          arrivalTime: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          categoryPuid: [{
            required: true,
            message: "上级类别不能为空",
            trigger: "blur"
          }],
          categoryName: [{
            required: true,
            message: "类别名称不能为空",
            trigger: "blur"
          }],
          dataPriority: [{
            required: true,
            message: "排序不能为空",
            trigger: "blur"
          }]
        }
      };
    },
    created() {
      this.getList();
      // this.getDicts("product_category_depth").then(response => {
      //   this.categoryDepthOptions = response.data;
      // });
      this.getDicts("sys_data_status").then(response => {
        this.statusOptions = response.data;
      });
      this.getDicts("product_category_show").then(response => {
        this.isShowOptions = response.data;
      });
      this.getDicts("product_arrival_time").then(response => {
        this.arrivalTimeOptions = response.data;
      });
    },
    methods: {
      isNull(value) {
        if (value != null && value != "") {
          return true;
        } else {
          false;
        }
      },
      /** 查询服务类别列表 */
      getList() {
        this.loading = true;
        listCategory(this.queryParams).then(response => {
          this.categoryList = this.handleTree(response.data, "categoryUid", "categoryPuid");
          this.loading = false;
        });
      },
      /** 转换服务类别数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.categoryUid,
          label: node.categoryName,
          children: node.children
        };
      },
      // 是否展示(1/展示，0/不展示)字典翻译
      categoryDepthFormat(row, column) {
        return this.selectDictLabel(this.categoryDepthOptions, row.categoryDepth);
      },
      // 是否展示(1/展示，0/不展示)字典翻译
      isShowFormat(row, column) {
        return this.selectDictLabel(this.isShowOptions, row.isShow);
      },
      // 发货时间字典翻译
      arrivalTimeFormat(row, column) {
        return this.selectDictLabel(this.arrivalTimeOptions, row.arrivalTime);
      },


      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          categoryPuid: "0",
          categoryName: null,
          dataStatus: "1",
          categoryDepth: 0,
          isShow: "1",
          arrivalTime: null,
          dataPriority: 10
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 状态修改
      handleStatusChange(row) {
        let text = row.dataStatus === "0" ? "无效" : "有效";
        this.$confirm('确定要把类别名称为"' + row.categoryName + '"设为' + text + '吗？', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return updateCategoryStatus(row.categoryUid, row.dataStatus, row.categoryDepth, row.categoryPuid);
        }).then(() => {
          this.msgSuccess("操作成功");
          this.getList();
        }).catch(function() {
          row.dataStatus = row.dataStatus === "0" ? "1" : "0";
        });
      },
      handleShowChange(row) {
        let text = row.isShow === "0" ? "隐藏" : "展示";
        this.$confirm('确定要把类别名称为"' + row.categoryName + '"设为' + text + '吗？', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return updateCategoryIsShow(row.categoryUid, row.isShow, row.categoryDepth, row.categoryPuid);
        }).then(() => {
          this.msgSuccess("操作成功");
          this.getList();
        }).catch(function() {
          row.isShow = row.isShow === "0" ? "1" : "0";
        });
      },
      /** 新增按钮操作 */
      handleAdd(row) {
        this.reset();
        if (row != null && row.categoryUid) {
          this.form.categoryPuid = row.categoryUid;
          this.form.categoryDepth = row.categoryDepth + 1;
          listCategoryDepth(row.categoryDepth).then(response => {
            this.categoryDepthList = response.data;
            this.open = true;
            this.title = "添加服务类别";
          });
        } else {
          this.categoryDepthList = [{
            categoryName: "顶级分类",
            categoryUid: "0"
          }];
          this.form.categoryDepth = "0";
          this.open = true;
          this.title = "添加服务类别";
        }


      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        getCategory(row.categoryUid).then(response => {
          this.form = response.data;
          if (this.form.categoryDepth == 0) {
            this.categoryDepthList = [{
              categoryName: "顶级分类",
              categoryUid: "0"
            }];
            this.form.categoryPuid = "0";
            this.open = true;
            this.title = "修改服务类别";
          } else {
            listCategoryDepth(row.categoryDepth - 1).then(response => {
              this.categoryDepthList = response.data;
              this.open = true;
              this.title = "修改服务类别";
            });
          }
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs.child.selectImg();
        this.$refs.childs.selectImgs();
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.categoryUid != null) {
              updateCategory(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addCategory(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        this.$confirm('是否确认删除服务类别名称为"' + row.categoryName + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delCategory(row.categoryUid);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
      }
    }
  };
</script>
<style scoped="scoped">
  .img-text {
    position: relative;
    /* top: -9px; */
  }
  .show_cate_info {
    display: flex;
    align-items: center;
  }
</style>

<style lang="scss">
  .pro_cate_mgr_content {
    .el-table .cell {
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
</style>
